package com.unipay.controller;

import com.unipay.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @BelongsProject: SSM
 * @Author: cmy
 * @CreateTime: 2023-01-19  16:33
 * @Description: TODO SpringMVC获取请求参数
 */
@Controller
@RequestMapping("/param")
public class ParamController {

    @RequestMapping("/")
    public String protal(){
        // 将逻辑视图返回：逻辑视图 加 配置文件中的“视图前缀、视图后缀” = 物理视图
        return "index";
    }

    // 1、通过ServletAPI获取
    //将HttpServletRequest作为控制器方法的形参，此时HttpServletRequest类型的参数表示“封装了当前请求的请求报文”的对象
    @RequestMapping("servletAPI")
    public String servletAPI(HttpServletRequest httpServletRequest){
        String username = httpServletRequest.getParameter("username");
        String password = httpServletRequest.getParameter("password");
        System.out.println("username: " + username + ", password: " + password);
        return "success";
    }
    // 2、通过控制器方法的形参获取请求参数
    // 3、@RequestParam：将请求参数和控制器方法的形参，创建映射关系
    @RequestMapping("formParam")
    public String formParam(@RequestParam(value = "Username",defaultValue = "cmy") String username, @RequestParam(required = false) String password){
        System.out.println("username: " + username + ", password: " + password);
        return "success";
    }
    // 4、@RequestHeader
    //@RequestHeader是将请求头信息和控制器方法的形参创建映射关系
    //@RequestHeader注解一共有三个属性：value、required、defaultValue，用法同@RequestParam
    @RequestMapping("head")
    public String head(@RequestHeader(value = "Referer") String referer,
                       @RequestParam(value = "Username",defaultValue = "cmy") String username,
                       @RequestParam(value = "passWord", required = false) String password){
        System.out.println("Referer: " + referer);
        System.out.println("username: " + username + ", password: " + password);
        return "success";
    }

    // ## 6、通过POJO获取请求参数
    // 可以在控制器方法的形参位置: 设置一个实体类类型的形参，
    // 此时若浏览器传输的请求参数的参数名和实体类中的属性名一致，那么请求参数就会为此属性赋值
    @RequestMapping("pojo")
    public String pojo(User user){
        System.out.println(user);
        return "success";
    }
}
